package com.sise.bl.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sise.bl.adapter.UserAdapter;
import com.sise.bl.entity.*;
import com.sise.bl.service.*;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/admins")
@SessionAttributes({"goodsTypeList", "goodsList", "loginUser"})
public class AdminController {
    @Autowired
    @Qualifier("typeService")
    private TypeService typeService;
    @Autowired
    @Qualifier("productService")
    private ProductService productService;
    @Autowired
    @Qualifier("userService")
    private UserService userService;
    @Autowired
    @Qualifier("ordersService")
    private OrdersService ordersService;
    @Autowired
    @Qualifier("adminService")
    private AdminService adminService;

    @RequestMapping(value = "/show")
    @ResponseBody
    public ModelAndView show(ModelAndView modelAndView) {
        List<Type> types = typeService.findAll();

        modelAndView.addObject("goodsTypeList", types);
        modelAndView.setViewName("admin/showGoodsType");
        return modelAndView;
    }

    @RequestMapping(value = "/getGoodsList")
    public ModelAndView getGoodsList(ModelAndView modelAndView) {
        List<Product> products = productService.queryAll();

        modelAndView.addObject("goodsList", products);
        modelAndView.setViewName("admin/showGoods");
        return modelAndView;
    }

    @RequestMapping(value = "/getAllOrder")
    public ModelAndView getAllOrder(ModelAndView modelAndView) {
        List<Orders> ordersList = ordersService.queryAll();
        modelAndView.addObject("orderList", ordersList);
        modelAndView.setViewName("admin/showAllOrder");
        return modelAndView;
    }

    @RequestMapping(value = "/getUserList")
    @ResponseBody
    public String getUserList() {
        List<User> users = userService.queryAll();
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(User.class, new UserAdapter());
        Gson gson = gsonBuilder.create();

//        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        String json = gson.toJson(users);
        return json;
    }

    @RequestMapping(value = "/deleteUser")
    public String deleteUser(@RequestParam("id") String id) {
        adminService.removeUserById(id);
        System.out.println(id);
        return "redirect:/admins/getUserList";
    }

    @RequestMapping(value = "/deleteType")
    public String deleteType(@RequestParam("tid") String tid) {
        adminService.removeType(tid);
        return "redirect:/admins/show";
    }

    @RequestMapping(value = "/deleteProduct")
    public String deleteProduct(@RequestParam("pid") String pid) {
        adminService.removeProductById(pid);
        return "redirect:/admins/getGoodsList";
    }

    //修改商品
    @RequestMapping(value = "/editProduct/{pid}")
    public ModelAndView editProduct(@PathVariable("pid") String pid, Model model) {
        ModelAndView modelAndView = new ModelAndView("admin/editGoods");
        //获取管理员信息
        User user = (User) model.getAttribute("loginUser");
        //查询所有分类的集合
        List<Type> types = typeService.findAll();
        modelAndView.addObject("types", types);
        //查询商品
        Product product = productService.findProductByPid(pid);
        modelAndView.addObject("admin", user);
        modelAndView.addObject("product", product);
        return modelAndView;
    }

    //更新商品
    @RequestMapping(value = "/updateProduct")
    public ModelAndView updateProduct(@ModelAttribute("product") Product product
            , @RequestParam(value = "picture", required = false) CommonsMultipartFile upload, HttpServletRequest request, Integer typeid) {
        ServletContext servletContext = request.getSession().getServletContext();
        //查询该商品
        Product oldProduct = productService.findProductByPid(product.getPid().toString());

        //获取文件的名称
        String uploadFilename = upload.getOriginalFilename();
        //如果上传的图片的名称不为空
        if (!"".equals(uploadFilename) && uploadFilename != null) {
            //获取文件保存目录
            String path = servletContext.getRealPath("/static/image");
            try {
                String savePath = path + "/" + uploadFilename;
                FileUtils.writeByteArrayToFile(new File(savePath), upload.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            //重新设置文件的路径
            product.setPimage("static/image/" + uploadFilename);
            //更新商品的时间
            product.setPtime(new Date());
            //删除旧的商品图片
            path = request.getSession().getServletContext().getRealPath("/" + oldProduct.getPimage());
            File file = new File(path);
            file.delete();
        } else {
            product.setPtime(new Date());
        }
        //更新商品
        if (typeid != null) {
            Type type1 = oldProduct.getType();
            type1.getProducts().remove(oldProduct);
            //该商品所属的分类
            Type type = typeService.queryTypeByid(typeid);
            product.setType(type);
            type.getProducts().add(product);
        }
        adminService.modifyProduct(product);
        return new ModelAndView("redirect:/admins/getGoodsList");
    }

    @RequestMapping(value = "/searchUser")
    public String searchUser(@RequestParam("username") String username) {
        User user = userService.queryByName(username);
        return null;
    }
}
